package com.tuanzi.loan.web.bean.system;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import org.primefaces.event.TreeDragDropEvent;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.business.entity.system.Menu;
import com.tuanzi.loan.business.service.system.MenuService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.loan.web.domain.MenuDomain;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class MenuBean extends JSFInfoBean<Menu> {

	private static final long serialVersionUID = -4109521771919671652L;
	@Autowired
	private MenuService menuService;

	private MenuDomain menuDomain;

	private TreeNode root;
	private TreeNode selectedNode;
	private Menu selectedMenu;

	@PostConstruct
	private void init() {
		menuDomain = new MenuDomain();
		root = menuDomain.generateTreeNode();
	}

	public void onSelectNode() {
		Menu menu = (Menu) selectedNode.getData();
		if (menu.getId() != null) {
			selectedMenu = menu;
			$ = selectedMenu;
		} else {
			selectedMenu = null;
			$ = null;
		}
		changeStatusToView();
	}

	public void onAddMenu() {
		if (selectedNode == null) {
			addWarnMessage("请选择菜单节点");
			return;
		}

		Menu menu = (Menu) selectedNode.getData();

		if (menu.getLeaf()) {
			addWarnMessage("不能添加菜单到叶子节点下");
			return;
		}

		$ = new Menu();
		changeStatusToAdd();
	}

	public void onCancel() {
		$ = selectedMenu;
		changeStatusToView();
	}

	public void onSaveMenu() {
		if ($.getId() == null && selectedMenu != null) {
			$.setParentId(selectedMenu.getId());
		}
		$ = menuService.saveOrUpdate($);
		addSuccessfullyMessage();
		changeStatusToView();
		refresh();
	}

	public void onDisableMenu() {
		menuService.recurseDisable($);
		addSuccessfullyMessage();
		refresh();
	}

	public void onEnableMenu() {
		menuService.enable($);
		addSuccessfullyMessage();
		refresh();
	}

	public void onDeleteMenu() {
		menuService.recurseDelete($);
		addSuccessfullyMessage();
		refresh();
	}

	public void onMoveMenu(TreeDragDropEvent event) {
		Menu dragMenu = (Menu) event.getDragNode().getData();
		Menu dropMenu = (Menu) event.getDropNode().getData();

		if (dropMenu.getLeaf()) {
			addWarnMessage("不能移动菜单到叶子菜单下");
		} else {
			menuService.moveMenu(dragMenu, dropMenu);
			addSuccessfullyMessage();
		}
		refresh();
	}

	private void refresh() {
		root = menuDomain.generateTreeNode();
		selectedNode = null;
		$ = null;
	}

}
